/**
 * Copyright (C) 2018-2019
 * All rights reserved, Designed By www.joolun.com
 */
package com.joolun.web.api;

import com.joolun.common.core.domain.R;
import com.joolun.script.entity.WxUserExt;
import com.joolun.script.service.WxUserExtService;
import com.joolun.web.vo.WxUserVO;
import com.joolun.weixin.constant.YesNoEnum;
import com.joolun.weixin.entity.LoginMaDTO;
import com.joolun.weixin.entity.WxOpenDataDTO;
import com.joolun.weixin.entity.WxUser;
import com.joolun.weixin.service.WxUserService;
import com.joolun.weixin.utils.ThirdSessionHolder;
import com.joolun.weixin.utils.WxMaUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 微信用户
 *
 * @author www.joolun.com
 * @date 2019-08-25 15:39:39
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/weixin/api/ma/wxuser")
@Api(value = "wxuser", tags = "小程序用户API")
public class WxUserApi {

    private static final ThreadLocal<Boolean> THREAD_LOCAL = new ThreadLocal<>();

    private final WxUserService wxUserService;

    private final WxUserExtService wxUserExtService;

    /**
     * 小程序用户登录
     *
     * @param request
     * @param loginMaDTO
     * @return
     */
    @ApiOperation(value = "小程序用户登录")
    @PostMapping("/login")
    public R<WxUserVO> login(HttpServletRequest request, @RequestBody LoginMaDTO loginMaDTO) {
        try {
            THREAD_LOCAL.set(Boolean.FALSE);
            String appId = WxMaUtil.getAppId(request);
            WxUser wxUser = wxUserService.loginMa(appId, loginMaDTO.getJsCode(), THREAD_LOCAL);
            if (THREAD_LOCAL.get()) {
                wxUserExtService.addExt(wxUser);
            }
            WxUserExt wxUserExt = wxUserExtService.getByUserId(wxUser.getId());
            if (Objects.nonNull(wxUserExt)) {
                wxUserService.cacheSessionKey(appId, wxUser, YesNoEnum.YES.getValue().equals(wxUserExt.getIsAdmin()));
            } else {
                wxUserService.cacheSessionKey(appId, wxUser, Boolean.FALSE);
            }

            return R.ok(toVO(wxUser));
        } catch (Exception e) {
            e.printStackTrace();
            return R.ok();
        } finally {
            THREAD_LOCAL.remove();
        }
    }

    private WxUserVO toVO(WxUser wxUser) {
        WxUserVO vo = new WxUserVO();
        if (Objects.nonNull(wxUser)) {
            wxUser.setSessionKey(null);
            BeanUtils.copyProperties(wxUser, vo);
            WxUserExt wxUserExt = wxUserExtService.getByUserId(wxUser.getId());
            vo.setExt(wxUserExt);
        }
        return vo;
    }

    /**
     * 获取用户信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "获取用户信息")
    @GetMapping
    public R<WxUserVO> get() {
        String id = ThirdSessionHolder.getThirdSession().getWxUserId();
        WxUser wxUser = wxUserService.getById(id);
        return R.ok(toVO(wxUser));
    }

    /**
     * 保存用户信息
     *
     * @param wxOpenDataDTO
     * @return
     */
    @ApiOperation(value = "保存用户信息")
    @PostMapping
    public R<WxUserVO> saveOrUptateWxUser(@RequestBody WxOpenDataDTO wxOpenDataDTO) {
        wxOpenDataDTO.setAppId(ThirdSessionHolder.getThirdSession().getAppId());
        wxOpenDataDTO.setUserId(ThirdSessionHolder.getThirdSession().getWxUserId());
        wxOpenDataDTO.setSessionKey(ThirdSessionHolder.getThirdSession().getSessionKey());
        WxUser wxUser = wxUserService.saveOrUptateWxUser(wxOpenDataDTO);
        if (StringUtils.isNotBlank(wxOpenDataDTO.getSchool())) {
            wxUserExtService.updateByUserId(wxUser.getId(), wxOpenDataDTO.getSchool());
        }
        return R.ok(toVO(wxUser));
    }

}
